package com.erp.collect.controller;

import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.ae.api.RemoteAeCategoryService;
import com.ruoyi.ae.api.RemoteAeProductService;
import com.ruoyi.collect.api.domain.*;
import com.erp.collect.domain.ErpCollectProductDistributeLog;
import com.erp.collect.mapper.*;
import com.erp.collect.service.IErpCollectProductCommonService;
import com.erp.collect.service.IErpCollectProductDistributeLogService;
import com.erp.collect.service.IErpKakaCollectProductService;
import com.erp.collect.service.IErpKakaImgFenliService;
import com.erp.collect.service.impl.ErpKakaCollectProductServiceImpl;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JsonUtils;
import com.ruoyi.common.core.utils.aliyun.PictureEditorUtils;
import com.ruoyi.common.core.utils.aliyun.TranslateImage;
import com.ruoyi.common.core.utils.bean.BeanCopyUtils;
import com.ruoyi.common.core.web.oldController.BaseController;
import com.ruoyi.freight.api.RemoteFreightService;
import com.ruoyi.freight.api.domain.AeProductFreight;
import com.ruoyi.gather.api.RemoteCollectProductService;
import com.ruoyi.gather.api.RemoteProductCategoryBrandService;
import com.ruoyi.gather.api.domain.Aliexpress;
import com.ruoyi.gather.api.domain.ErpCollectProduct;
import com.ruoyi.gather.api.domain.ErpCollectProductExpand;
import com.ruoyi.gather.api.domain.ErpCollectProductSku;
import com.ruoyi.gather.api.domain.dto.ComputeFreightDto;
import com.sun.org.apache.regexp.internal.RE;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 采集商品的合规处理
 *
 * @author erp
 * @date 2024-05-16
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/collect/product/handle")
public class ErpCollectProductHandleController extends BaseController {

    @Resource
    IErpCollectProductCommonService commonService;
    @Resource
    IErpCollectProductDistributeLogService distributeLogService;
    @Resource
    ErpKakaCollectProductMapper erpKakaCollectProductMapper;
    @Resource
    ErpKakaCollectProductExpandMapper erpKakaCollectProductExpandMapper;
    @Resource
    IErpKakaCollectProductService iErpKakaCollectProductService;
    @Resource
    ErpKakaCollectProductSkuMapper erpKakaCollectProductSkuMapper;
    @Resource
    ErpCollectProductAMapper erpCollectProductAMapper;
    @Resource
    ErpCollectProductExpandAMapper erpCollectProductExpandAMapper;
    @Resource
    ErpCollectProductSkuAMapper erpCollectProductSkuAMapper;

    @Resource
    ErpCollectProductBMapper erpCollectProductBMapper;
    @Resource
    ErpCollectProductExpandBMapper erpCollectProductExpandBMapper;
    @Resource
    ErpCollectProductSkuBMapper erpCollectProductSkuBMapper;

    @Resource
    ErpCollectProductDistributeLogMapper distributeLogMapper;
    @Resource
    RemoteFreightService remoteFreightService;
    @Resource
    RemoteCollectProductService remoteCollectProductService;
    @Resource
    RemoteProductCategoryBrandService remoteProductCategoryBrandService;
    @Resource
    IErpKakaImgFenliService fenliService;

    /**
     * AE速卖通的合规处理 设置定时任务进行处理
     */
    @GetMapping("/compliance/ae/kaka")
    public void complianceAeKaka(Long id, Integer type) {
        List<ErpCollectProductDistributeLog> distributeLogList = new ArrayList<>();
        if (Objects.isNull(id)) {
            //type = 0，正常执行，type = 1速卖通规格异常
            if (type == 0) {
                // 获取待分发的采集商品
                distributeLogList
                        = distributeLogService.getNoDistributionList("1688", "ae", 200);
                if (distributeLogList.size() == 0) {
                    return;
                }
            } else {
                // 获取待分发的采集商品
                distributeLogList
                        = distributeLogService.getErrorBySkuDistributionList("1688", "ae", 200);
                if (distributeLogList.size() == 0) {
                    return;
                }
            }


        } else {
            ErpCollectProductDistributeLog log = distributeLogMapper.selectOne(
                    new LambdaQueryWrapper<ErpCollectProductDistributeLog>()
                            .eq(ErpCollectProductDistributeLog::getCollectProductId, id)
                            .orderByDesc(ErpCollectProductDistributeLog::getCreateTime)
                            .last("limit 1")
            );
            distributeLogList.add(log);
        }

        // 更新状态，防止重复分发
        distributeLogList.forEach(item -> item.setDistributeAe("9"));
        distributeLogMapper.updateBatchById(distributeLogList);

        for (ErpCollectProductDistributeLog log : distributeLogList) {
            Long collectProductId = log.getCollectProductId();
            //获取目标的商品
            ErpKakaCollectProduct product = erpKakaCollectProductMapper.selectById(log.getCollectProductId());
            ErpKakaCollectProductExpand productExpand = erpKakaCollectProductExpandMapper.selectOne(
                    new LambdaQueryWrapper<ErpKakaCollectProductExpand>().eq(ErpKakaCollectProductExpand::getCollectProductId, collectProductId)
            );
            List<ErpKakaCollectProductSku> skuList = erpKakaCollectProductSkuMapper.selectList(
                    new LambdaQueryWrapper<ErpKakaCollectProductSku>()
                            .eq(ErpKakaCollectProductSku::getCollectProductId, collectProductId)
            );
            if (Objects.isNull(product)) {
                log.setDistributeAe("2");
                log.setAeLog("查找商品不存在");
                distributeLogMapper.updateById(log);
                continue;
            }

            if (type == 1) {
                //是需要合并规格的，进行规格合并
                ComputeFreightDto skuDto = new ComputeFreightDto();
                skuDto.setProduct(JSONObject.parseObject(JSONObject.toJSONString(product)));
                skuDto.setProductExpand(JSONObject.parseObject(JSONObject.toJSONString(productExpand)));
                skuDto.setProductSkuList(JSONArray.parseArray(JSONObject.toJSONString(skuList)));
                ComputeFreightDto returnSkuDto = updateCateGoryProById(skuDto);
                if (ObjectUtils.isNotNull(returnSkuDto)) {
                    product = JSONObject.parseObject(returnSkuDto.getProduct().toString(), ErpKakaCollectProduct.class);
                    productExpand = JSONObject.parseObject(returnSkuDto.getProductExpand().toString(), ErpKakaCollectProductExpand.class);
                    skuList = JSONArray.parseArray(returnSkuDto.getProductSkuList().toString(), ErpKakaCollectProductSku.class);
                }
            }

            // TODO 1、标题翻译
            product.setSubject(commonService.translate(product.getSubject()));
            // TODO 2、详情翻译
            if (ObjectUtils.isNotNull(product.getDetail())) {
                product.setDetail(commonService.translate(product.getDetail()));
            }
            // TODO 3、主图轮播图、详情图 图片翻译
            String imgRegex = ";";
            String rePath = "";
            StringBuffer rePathUrls = new StringBuffer();
            // 主图链接替换
            String imageURLs = product.getImageURLs();
            if (ObjectUtils.isNotNull(imageURLs)) {
                //将逗号改为分号
                imageURLs = imageURLs.replace(",", ";");
                String[] mainUrls = imageURLs.split(imgRegex);
                for (String mainUrl : mainUrls) {
                    rePath = fenliService.getRePathByOldUrl(mainUrl);
                    if (ObjectUtils.isNotNull(rePath)) {
                        rePath = rePath.replace("\\", "/");
                        rePath = "http://120.224.119.46:8880/" + rePath;
                    }
                    rePathUrls.append(";");
                    rePathUrls.append((rePath == null || rePath.equals("")) ? mainUrl : rePath);
                }
                product.setImageURLs(rePathUrls.toString().replaceFirst(";", ""));
            }


            // 详情图替换
            String detailImg = product.getDetailImg();
            if (ObjectUtils.isNotNull(detailImg)) {
                detailImg = detailImg.replace(",", ";");
                String[] detailUrls = detailImg.split(imgRegex);
                rePathUrls = new StringBuffer();
                for (String detailUrl : detailUrls) {
                    rePath = fenliService.getRePathByOldUrl(detailUrl);
                    if (ObjectUtils.isNotNull(rePath)) {
                        rePath = rePath.replace("\\", "/");
                        rePath = "http://120.224.119.46:8880/" + rePath;
                    }
                    rePathUrls.append(";");
                    rePathUrls.append((rePath == null || rePath.equals("")) ? detailUrl : rePath);
                }
                product.setDetailImg(rePathUrls.toString().replaceFirst(";", ""));
            }

            //TODO 晓翔接口，维护商品属性
            if (Objects.isNull(product.getCategoryId())) {
                R<Object> objectR = remoteCollectProductService.queryCategoryBySubject(product.getSubject());
                if (objectR.getCode() == 200) {
                    Long categoryId = (Long) objectR.getData();
                    product.setCategoryId(categoryId);
                } else {
                    log.setDistributeAe("3");
                    log.setAeLog("根据标题查找类目失败");
                    distributeLogMapper.updateById(log);
                    continue;
                }
            }

            R<String> customAttributesObj = updateCustomAttributesByCategory(product.getCategoryId());
            int code = customAttributesObj.getCode();
            if (code != 200){
                log.setDistributeAe("3");
                log.setAeLog(customAttributesObj.getMsg());
                distributeLogMapper.updateById(log);
                continue;
            }
            if (ObjectUtils.isNotNull(customAttributesObj.getData())) {
                product.setCustomAttributes(customAttributesObj.getData());
                //T用新属性替换原属性暂时
//                customAttributes = customAttributes.substring(0, customAttributes.length() - 1) + ",";
//                product.setCustomAttributes(product.getCustomAttributes().replaceFirst("\\[", customAttributes));
            }else {
                product.setCustomAttributes(null);
            }

            // TODO 4、sku名称翻译、与sku图片合并、长度是否超过20个字符 调 孙 翻译接口
            // 使用ASCII码值对应字母
            int startSku = 65;
            List<ErpCollectProductSkuA> skuAList = new ArrayList<>();
            for (ErpKakaCollectProductSku sku : skuList) {
                if (sku.getSkuImage() != null && !sku.getSkuImage().equals("")) {
                    // sku有图片的，取合成图片
                    rePath = fenliService.getRePathByOldUrl(sku.getSkuImage());
                    if (ObjectUtils.isNotNull(rePath)) {
                        rePath = rePath.replace("\\", "/");
                        rePath = "http://120.224.119.46:8880/" + rePath;
                    }
                    sku.setSkuImage((rePath == null || rePath.equals("")) ? sku.getSkuImage() : rePath);
                    // 重命名sku名称 A B C ...
                    sku.setSkuName(startSku > 90 ? (startSku + "") : String.valueOf((char) startSku));
                    startSku++;
                } else {
                    if (Objects.isNull(sku.getSkuName())) {
                        sku.setSkuName(String.valueOf((char) startSku));
                        startSku++;
                    } else {
                        // 直接翻译
                        sku.setSkuName(commonService.translate(sku.getSkuName()));
                        //判断长度是否超过20个字符
                        if (sku.getSkuName().length() > 20) {
                            sku.setSkuName(sku.getSkuName().substring(0, 20));
                        }
                    }
                }

                ErpCollectProductSkuA skua = BeanCopyUtils.copy(sku, ErpCollectProductSkuA.class);

                skua.setSkuWidth(Objects.isNull(skua.getSkuWidth()) ? BigDecimal.TEN : skua.getSkuWidth());
                skua.setSkuLength(Objects.isNull(skua.getSkuLength()) ? BigDecimal.TEN : skua.getSkuLength());
                skua.setSkuHeight(Objects.isNull(skua.getSkuHeight()) ? BigDecimal.TEN : skua.getSkuHeight());
                skua.setId(null);
                skuAList.add(skua);
            }
            // TODO 5、获取重量的中位数，并运费试算 使用64个国家的运费试算
            String grossWeight = product.getGrossWeight();
            BigDecimal grossWeightDec = new BigDecimal(grossWeight);
            // 检查grossWeight是否大于150g（假设是克为单位）
            if (grossWeightDec.compareTo(new BigDecimal("150")) > 0) {
                // 如果grossWeight在150g到2000g之间（包括2000g）
                if (grossWeightDec.compareTo(new BigDecimal("2000")) <= 0) {
                    // 按grossWeight上浮10%
                    BigDecimal increasedWeight = grossWeightDec.multiply(new BigDecimal("1.10")).setScale(2, BigDecimal.ROUND_HALF_UP); // 设置小数位数和舍入模式
                    // 接下来你可以使用increasedWeight来进行后续操作
                    System.out.println("上浮10%后的重量为: " + increasedWeight);
                    grossWeight = increasedWeight.toString();
                } else {
                    // 如果grossWeight超过2000g
                    // 这里可以添加记录失败原因的逻辑
                    log.setDistributeAe("2");
                    log.setAeLog("产品重量超过2000g，需要人工审核");
                    distributeLogMapper.updateById(log);
                    continue;
                }
            } else {
                //小于一百五统一按一百五来 528
                grossWeight = "150";
            }
            product.setGrossWeight(grossWeight);
            AeProductFreight freight = new AeProductFreight();
            freight.setHeight("10");
            freight.setLength("10");
            freight.setWidth("10");
            freight.setWeight(grossWeight);
            // 试算模版 菜鸟标准
            freight.setType(0);
            ComputeFreightDto dto = new ComputeFreightDto();
            dto.setProduct(JSONObject.parseObject(JSONObject.toJSONString(product)));
            dto.setProductExpand(JSONObject.parseObject(JSONObject.toJSONString(productExpand)));
            dto.setProductSkuList(JSONArray.parseArray(JSONObject.toJSONString(skuAList)));
            R<Object> objectRA = remoteFreightService.computeFreightWith64(dto);
            String returnStrA = JSONObject.toJSONString(objectRA.getData());
            ComputeFreightDto computeFreightDtoA = JSONObject.parseObject(returnStrA, ComputeFreightDto.class);
            System.out.println(computeFreightDtoA);

            ErpCollectProduct returnProductA = JSONObject.parseObject(computeFreightDtoA.getProduct().toString(), ErpCollectProduct.class);
            ErpCollectProductExpand returnProductExpandA = JSONObject.parseObject(computeFreightDtoA.getProductExpand().toString(), ErpCollectProductExpand.class);
            List<ErpCollectProductSku> returnProductSkuA = JSONArray.parseArray(computeFreightDtoA.getProductSkuList().toString(), ErpCollectProductSku.class);

            // TODO 6、测试发布
            // 创建task任务
//            ErpKakaCollectProductUploadTestTask task = new ErpKakaCollectProductUploadTestTask();
//            task.setStatus(0);
//            task.setType("1688");
//            task.setCollectProductId(collectProductId);
//            task.setAddTime(new Date());
//            erpKakaCollectProductUploadTestTaskMapper.insert(task);

            // TODO 7、成功后再入单独产品库，失败则记录原因
            //修改商品的sku属性
            dto.setProduct(JSONObject.parseObject(JSONObject.toJSONString(returnProductA)));
            dto.setProductExpand(JSONObject.parseObject(JSONObject.toJSONString(returnProductExpandA)));
            dto.setProductSkuList(JSONArray.parseArray(JSONObject.toJSONString(returnProductSkuA)));
            R<Object> objectRB = remoteCollectProductService.updateSkuPropertyByProductA(dto);
            if (objectRB.getCode() != 200) {
                log.setDistributeAe("2");
                log.setAeLog(objectRB.getMsg());
                distributeLogMapper.updateById(log);
                continue;
            }
            String returnStrB = JSONObject.toJSONString(objectRB.getData());
            ComputeFreightDto computeFreightDtoB = JSONObject.parseObject(returnStrB, ComputeFreightDto.class);
            System.out.println(computeFreightDtoB);

            ErpCollectProductA returnProductB = JSONObject.parseObject(computeFreightDtoB.getProduct().toString(), ErpCollectProductA.class);
            ErpCollectProductExpandA returnProductExpandB = JSONObject.parseObject(computeFreightDtoB.getProductExpand().toString(), ErpCollectProductExpandA.class);
//            ErpCollectProductA collectProductB = BeanCopyUtils.copy(returnProductB, ErpCollectProductA.class);
//            ErpCollectProductExpandA collectProductExpandB = BeanCopyUtils.copy(returnProductExpandB, ErpCollectProductExpandA.class);
            List<ErpCollectProductSkuA> returnProductSkuB = JSONArray.parseArray(computeFreightDtoB.getProductSkuList().toString(), ErpCollectProductSkuA.class);
            returnProductExpandB.setProductStatus(Long.valueOf(1));
            erpCollectProductExpandAMapper.insertOrUpdate(returnProductExpandB);
            erpCollectProductAMapper.insertOrUpdate(returnProductB);
            erpCollectProductSkuAMapper.insertOrUpdateBatch(returnProductSkuB);
            log.setDistributeAe("1");
            log.setAeLog("导入成功");
            distributeLogMapper.updateById(log);
        }
    }

    /**
     * 薇薇宝版
     *
     * @param id
     * @param type
     */
    @GetMapping("/compliance/ae/wwb")
    public void complianceAeWWB(Long id, Integer type) {
        List<ErpCollectProductDistributeLog> distributeLogList = new ArrayList<>();
        if (Objects.isNull(id)) {
            //type = 0，正常执行，type = 1速卖通规格异常
            if (type == 0) {
                // 获取待分发的采集商品
                distributeLogList
                        = distributeLogService.getNoDistributionList("wwb", "ae", 100);
                if (distributeLogList.size() == 0) {
                    return;
                }
            } else {
                // 获取待分发的采集商品
                distributeLogList
                        = distributeLogService.getErrorBySkuDistributionList("wwb", "ae", 100);
                if (distributeLogList.size() == 0) {
                    return;
                }
            }


        } else {
            ErpCollectProductDistributeLog log = distributeLogMapper.selectOne(
                    new LambdaQueryWrapper<ErpCollectProductDistributeLog>()
                            .eq(ErpCollectProductDistributeLog::getCollectProductId, id)
                            .orderByDesc(ErpCollectProductDistributeLog::getCreateTime)
                            .last("limit 1")
            );
            distributeLogList.add(log);
        }

        // 更新状态，防止重复分发
        distributeLogList.forEach(item -> item.setDistributeAe("9"));
        distributeLogMapper.updateBatchById(distributeLogList);

        for (ErpCollectProductDistributeLog log : distributeLogList) {
            Long collectProductId = log.getCollectProductId();
            //获取目标的商品
            ErpCollectProductB product = erpCollectProductBMapper.selectById(log.getCollectProductId());
            ErpCollectProductExpandB productExpand = erpCollectProductExpandBMapper.selectOne(
                    new LambdaQueryWrapper<ErpCollectProductExpandB>().eq(ErpCollectProductExpandB::getCollectProductId, collectProductId)
            );
            List<ErpCollectProductSkuB> skuList = erpCollectProductSkuBMapper.selectList(
                    new LambdaQueryWrapper<ErpCollectProductSkuB>()
                            .eq(ErpCollectProductSkuB::getCollectProductId, collectProductId)
            );
            if (Objects.isNull(product)) {
                log.setDistributeAe("2");
                log.setAeLog("查找商品不存在");
                distributeLogMapper.updateById(log);
                continue;
            }

            if (type == 1) {
                //是需要合并规格的，进行规格合并
                ComputeFreightDto skuDto = new ComputeFreightDto();
                skuDto.setProduct(JSONObject.parseObject(JSONObject.toJSONString(product)));
                skuDto.setProductExpand(JSONObject.parseObject(JSONObject.toJSONString(productExpand)));
                skuDto.setProductSkuList(JSONArray.parseArray(JSONObject.toJSONString(skuList)));
                ComputeFreightDto returnSkuDto = updateCateGoryProById(skuDto);
                if (ObjectUtils.isNotNull(returnSkuDto)) {
                    product = JSONObject.parseObject(returnSkuDto.getProduct().toString(), ErpCollectProductB.class);
                    productExpand = JSONObject.parseObject(returnSkuDto.getProductExpand().toString(), ErpCollectProductExpandB.class);
                    skuList = JSONArray.parseArray(returnSkuDto.getProductSkuList().toString(), ErpCollectProductSkuB.class);
                }
            }


            // TODO 3、主图轮播图、详情图 图片翻译
            String imgRegex = ";";
            String rePath = "";
            StringBuffer rePathUrls = new StringBuffer();
            // 主图链接替换
            String imageURLs = product.getImageURLs();
            if (ObjectUtils.isNotNull(imageURLs)) {
                //将逗号改为分号
                imageURLs = imageURLs.replace(",", ";");
                String[] mainUrls = imageURLs.split(imgRegex);
                String newUrl = null;
                for (String mainUrl : mainUrls) {
                    newUrl = mainUrl;
                    // 找到?的位置
                    int index = mainUrl.indexOf("?");
                    // 如果找到了?
                    if (index != -1) {
                        // 分割字符串并取第一部分（即?之前的内容）
                        String[] parts = mainUrl.split("\\?", 2); // 使用2作为限制参数，只分割一次
                        // 如果URL以.jpg结尾（或其他图片格式），则保持不变，否则添加.jpg
                        if (parts[0].endsWith(".jpg")) {
                            // 如果?之后没有内容且URL已经以.jpg结尾，则无需修改
                            newUrl = parts[0];
                        } else {
                            // 否则，用第一部分和.jpg重新组合URL
                            newUrl = parts[0] + ".jpg";
                        }
                    }
                    rePathUrls.append(";");
                    newUrl = TranslateImage.queryFinalImage(newUrl);
                    rePathUrls.append((rePath == null || rePath.equals("")) ? newUrl : rePath);
                }
                product.setImageURLs(rePathUrls.toString().replaceFirst(";", ""));
            }


            // 详情图替换
            String detailImg = product.getDetailImg();
            if (ObjectUtils.isNotNull(detailImg)) {
                detailImg = detailImg.replace(",", ";");
                String[] detailUrls = detailImg.split(imgRegex);
                rePathUrls = new StringBuffer();
                String newUrl = null;
                for (String detailUrl : detailUrls) {
                    // 找到?的位置
                    newUrl = detailUrl;
                    int index = detailUrl.indexOf("?");
                    // 如果找到了?
                    if (index != -1) {
                        // 分割字符串并取第一部分（即?之前的内容）
                        String[] parts = detailUrl.split("\\?", 2); // 使用2作为限制参数，只分割一次
                        // 如果URL以.jpg结尾（或其他图片格式），则保持不变，否则添加.jpg
                        if (parts[0].endsWith(".jpg")) {
                            // 如果?之后没有内容且URL已经以.jpg结尾，则无需修改
                            newUrl = parts[0];
                        } else {
                            // 否则，用第一部分和.jpg重新组合URL
                            newUrl = parts[0] + ".jpg";
                        }
                    }
                    rePathUrls.append(";");
                    newUrl = TranslateImage.queryFinalImage(newUrl);
                    rePathUrls.append((rePath == null || rePath.equals("")) ? newUrl : rePath);
                }
                product.setDetailImg(rePathUrls.toString().replaceFirst(";", ""));
            }
            //防止类目有问题
            if (Objects.isNull(product.getCategoryId())) {
                R<Object> objectR = remoteCollectProductService.queryCategoryBySubject(product.getSubject().replaceAll("/", ""));
                if (objectR.getCode() == 200) {
                    String categoryId = (String) objectR.getData();
                    product.setCategoryId(Long.valueOf(categoryId));
                } else {
                    log.setDistributeAe("2");
                    log.setAeLog("根据标题查找类目失败");
                    distributeLogMapper.updateById(log);
                    continue;
                }
            }
            //TODO 晓翔接口，维护商品属性
            R<String> customAttributesObj = updateCustomAttributesByCategory(product.getCategoryId());
            int code = customAttributesObj.getCode();
            if (code != 200){
                log.setDistributeAe("3");
                log.setAeLog(customAttributesObj.getMsg());
                distributeLogMapper.updateById(log);
                continue;
            }
            if (ObjectUtils.isNotNull(customAttributesObj.getData())) {
                product.setCustomAttributes(customAttributesObj.getData());
                //T用新属性替换原属性暂时
//                customAttributes = customAttributes.substring(0, customAttributes.length() - 1) + ",";
//                product.setCustomAttributes(product.getCustomAttributes().replaceFirst("\\[", customAttributes));
            }else {
                product.setCustomAttributes(null);
            }


            // TODO 1、标题翻译
            product.setSubject(commonService.translate(product.getSubject()));
            // TODO 2、详情翻译
            if (ObjectUtils.isNotNull(product.getDetail())) {
                product.setDetail(commonService.translate(product.getDetail()));
            }

            //TODO 属性翻译
            String skuProperty = productExpand.getSkuProperty(); // sku列表
            List<Dict> skuPropertyList = JsonUtils.parseArrayMap(skuProperty);
            for (Dict dict : skuPropertyList) {
                String name = (String) dict.get("name");
                String nameNew = commonService.translate(name);
                dict.put("name", nameNew);

                List<HashMap> skuValueList = (List<HashMap>) dict.get("list");
                for (HashMap dict2 : skuValueList) {
                    String valueName = (String) dict2.get("name");
                    String valueNameNew = commonService.translate(valueName);
                    dict2.put("name", valueNameNew);
                }
            }
            String skuPropertyNew = JsonUtils.toJsonString(skuPropertyList);
            productExpand.setSkuProperty(skuPropertyNew);


            // TODO 5、获取重量的中位数，并运费试算 使用64个国家的运费试算
            String grossWeight = product.getGrossWeight();
            BigDecimal grossWeightDec = new BigDecimal(grossWeight);
            // 检查grossWeight是否大于150g（假设是克为单位）
            if (grossWeightDec.compareTo(new BigDecimal("150")) > 0) {
                // 如果grossWeight在150g到2000g之间（包括2000g）
                if (grossWeightDec.compareTo(new BigDecimal("2000")) <= 0) {
                    // 按grossWeight上浮10%
                    BigDecimal increasedWeight = grossWeightDec.multiply(new BigDecimal("1.10")).setScale(2, BigDecimal.ROUND_HALF_UP); // 设置小数位数和舍入模式
                    // 接下来你可以使用increasedWeight来进行后续操作
                    System.out.println("上浮10%后的重量为: " + increasedWeight);
                    grossWeight = increasedWeight.toString();
                } else {
                    // 如果grossWeight超过2000g
                    // 这里可以添加记录失败原因的逻辑
                    log.setDistributeAe("2");
                    log.setAeLog("产品重量超过2000g，需要人工审核");
                    distributeLogMapper.updateById(log);
                    continue;
                }
            } else {
                //小于一百五统一按一百五来 528
                grossWeight = "150";
            }
            product.setGrossWeight(grossWeight);

            // TODO 4、sku名称翻译、与sku图片合并、长度是否超过20个字符 调 孙 翻译接口
            // 使用ASCII码值对应字母
            int startSku = 65;
            for (ErpCollectProductSkuB sku : skuList) {
                if (sku.getSkuImage() != null && !sku.getSkuImage().equals("")) {
                    // sku有图片的，取合成图片
                    String newUrl = sku.getSkuImage();
                    // 找到?的位置
                    int index = sku.getSkuImage().indexOf("?");
                    // 如果找到了?
                    if (index != -1) {
                        // 分割字符串并取第一部分（即?之前的内容）
                        String[] parts = sku.getSkuImage().split("\\?", 2); // 使用2作为限制参数，只分割一次
                        // 如果URL以.jpg结尾（或其他图片格式），则保持不变，否则添加.jpg
                        if (parts[0].endsWith(".jpg")) {
                            // 如果?之后没有内容且URL已经以.jpg结尾，则无需修改
                            newUrl = parts[0];
                        } else {
                            // 否则，用第一部分和.jpg重新组合URL
                            newUrl = parts[0] + ".jpg";
                        }
                    }
                    String skuImage = (newUrl == null || newUrl.equals("")) ? sku.getSkuName() : newUrl;
                    sku.setSkuImage(TranslateImage.queryFinalImage(skuImage));
                    // 重命名sku名称 A B C ...
                    sku.setSkuName(startSku > 90 ? (startSku + "") : String.valueOf((char) startSku));
                    startSku++;
                } else {
                    if (Objects.isNull(sku.getSkuName())) {
                        sku.setSkuName(String.valueOf((char) startSku));
                        startSku++;
                    } else {
                        // 直接翻译
                        sku.setSkuName(commonService.translate(sku.getSkuName()));
                        //判断长度是否超过20个字符
                        if (sku.getSkuName().length() > 20) {
                            sku.setSkuName(sku.getSkuName().substring(0, 20));
                        }
                    }
                }

//                ErpCollectProductSkuB skua = BeanCopyUtils.copy(sku, ErpCollectProductSkuB.class);

                sku.setSkuWidth(Objects.isNull(sku.getSkuWidth()) ? BigDecimal.TEN : sku.getSkuWidth());
                sku.setSkuLength(Objects.isNull(sku.getSkuLength()) ? BigDecimal.TEN : sku.getSkuLength());
                sku.setSkuHeight(Objects.isNull(sku.getSkuHeight()) ? BigDecimal.TEN : sku.getSkuHeight());
                sku.setSkuWeight(Objects.isNull(sku.getSkuWeight()) ? new BigDecimal(product.getGrossWeight()).longValue() : sku.getSkuWeight());
            }
            AeProductFreight freight = new AeProductFreight();
            freight.setHeight("10");
            freight.setLength("10");
            freight.setWidth("10");
            freight.setWeight(grossWeight);
            // 试算模版 菜鸟标准
            freight.setType(0);
            ComputeFreightDto dto = new ComputeFreightDto();
            dto.setProduct(JSONObject.parseObject(JSONObject.toJSONString(product)));
            dto.setProductExpand(JSONObject.parseObject(JSONObject.toJSONString(productExpand)));
            dto.setProductSkuList(JSONArray.parseArray(JSONObject.toJSONString(skuList)));
            R<Object> objectRA = remoteFreightService.computeFreightWith64(dto);
            String returnStrA = JSONObject.toJSONString(objectRA.getData());
            ComputeFreightDto computeFreightDtoA = JSONObject.parseObject(returnStrA, ComputeFreightDto.class);
            System.out.println(computeFreightDtoA);

            ErpCollectProduct returnProductA = JSONObject.parseObject(computeFreightDtoA.getProduct().toString(), ErpCollectProduct.class);
            ErpCollectProductExpand returnProductExpandA = JSONObject.parseObject(computeFreightDtoA.getProductExpand().toString(), ErpCollectProductExpand.class);
            List<ErpCollectProductSku> returnProductSkuA = JSONArray.parseArray(computeFreightDtoA.getProductSkuList().toString(), ErpCollectProductSku.class);

            // TODO 6、测试发布
            // 创建task任务
//            ErpKakaCollectProductUploadTestTask task = new ErpKakaCollectProductUploadTestTask();
//            task.setStatus(0);
//            task.setType("1688");
//            task.setCollectProductId(collectProductId);
//            task.setAddTime(new Date());
//            erpKakaCollectProductUploadTestTaskMapper.insert(task);

            // TODO 7、成功后再入单独产品库，失败则记录原因
            //修改商品的sku属性
            dto.setProduct(JSONObject.parseObject(JSONObject.toJSONString(returnProductA)));
            dto.setProductExpand(JSONObject.parseObject(JSONObject.toJSONString(returnProductExpandA)));
            dto.setProductSkuList(JSONArray.parseArray(JSONObject.toJSONString(returnProductSkuA)));
            R<Object> objectRB = remoteCollectProductService.updateSkuPropertyByProductA(dto);
            if (objectRB.getCode() != 200) {
                log.setDistributeAe("2");
                log.setAeLog(objectRB.getMsg());
                distributeLogMapper.updateById(log);
                continue;
            }
            String returnStrB = JSONObject.toJSONString(objectRB.getData());
            ComputeFreightDto computeFreightDtoB = JSONObject.parseObject(returnStrB, ComputeFreightDto.class);
            System.out.println(computeFreightDtoB);

            ErpCollectProductB returnProductB = JSONObject.parseObject(computeFreightDtoB.getProduct().toString(), ErpCollectProductB.class);
            ErpCollectProductExpandB returnProductExpandB = JSONObject.parseObject(computeFreightDtoB.getProductExpand().toString(), ErpCollectProductExpandB.class);
//            ErpCollectProductA collectProductB = BeanCopyUtils.copy(returnProductB, ErpCollectProductA.class);
//            ErpCollectProductExpandA collectProductExpandB = BeanCopyUtils.copy(returnProductExpandB, ErpCollectProductExpandA.class);
            List<ErpCollectProductSkuB> returnProductSkuB = JSONArray.parseArray(computeFreightDtoB.getProductSkuList().toString(), ErpCollectProductSkuB.class);
            returnProductExpandB.setProductStatus(Long.valueOf(1));
            erpCollectProductExpandBMapper.insertOrUpdate(returnProductExpandB);
            erpCollectProductBMapper.insertOrUpdate(returnProductB);
            erpCollectProductSkuBMapper.insertOrUpdateBatch(returnProductSkuB);
            log.setDistributeAe("1");
            log.setAeLog("导入成功");
            distributeLogMapper.updateById(log);
        }
    }


    @GetMapping("/compliance/updateCustomAttributesByCategory")
    public R<String> updateCustomAttributesByCategory(Long categoryId) {
        R<Object> objectR = remoteProductCategoryBrandService.getCategoryInfoByIdInner(categoryId);
        if (Objects.isNull(objectR.getData())) {
            return R.fail("类目不存在");
        }
        List<Aliexpress.CategoryInfoVo> categoryInfoByIdList = JSONArray.parseArray(JSONObject.toJSONString(objectR.getData()), Aliexpress.CategoryInfoVo.class);
        if (categoryInfoByIdList.size() == 0)
            return R.fail("类目信息为空");
        Map<String, Object> attrMap = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        for (Aliexpress.CategoryInfoVo categoryInfoVo : categoryInfoByIdList) {
            String required = categoryInfoVo.getRequired();
            String attrNameId = categoryInfoVo.getAttr_name_id().toString();

            if (required.equals("1") || attrNameId.equals("219")) { // 是必填项
                String attributeShowTypeValue = categoryInfoVo.getAttributeShowTypeValue();
                // 产地都是大陆
                if (categoryInfoVo.getAttr_name_id() == 219) {
                    attrMap = new HashMap<>();
                    attrMap.put("attr_name", "Origin");
                    attrMap.put("attr_name_id", 219);
                    attrMap.put("attr_value", null);
                    attrMap.put("attr_value_id", 9441741844L);
                    list.add(attrMap);
                    continue;
                }
                switch (attributeShowTypeValue) {
                    case "list_box":
                        // 下拉框，默认选第一个
                        attrMap = new HashMap<>();
                        attrMap.put("attr_name", categoryInfoVo.getAttr_name());
                        attrMap.put("attr_name_id", categoryInfoVo.getAttr_name_id());
                        attrMap.put("attr_value", null);
                        attrMap.put("attr_value_id", categoryInfoVo.getValues().get(0).getAttr_value_id());
                        list.add(attrMap);
                        break;
                    case "input":
                        attrMap = new HashMap<>();
                        attrMap.put("attr_name", null);
                        attrMap.put("attr_name_id", categoryInfoVo.getAttr_name_id());
                        attrMap.put("attr_value", "1");
                        attrMap.put("attr_value_id", null);
                        list.add(attrMap);
                        break;
                    case "check_box":
                        attrMap = new HashMap<>();
                        attrMap.put("attr_name", categoryInfoVo.getAttr_name());
                        attrMap.put("attr_name_id", categoryInfoVo.getAttr_name_id());
                        attrMap.put("attr_value", "1");
                        attrMap.put("attr_value_id", categoryInfoVo.getValues().get(0).getAttr_value_id());
                        list.add(attrMap);
                        break;
//                    case "interval":
//                    case "brand":
                }
            }
        }

        // 保存产品属性
        String customAttributes = JSONObject.toJSONString(list);
        System.out.println(customAttributes);
//        product.setCustomAttributes(customAttributes);
//        int update = baseMapper.updateById(product);
//        ErpCollectProductExpand collectProductExpand = erpCollectProductExpandMapper.selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
//                .eq(ErpCollectProductExpand::getCollectProductId, product.getId()));
        return R.ok(customAttributes,customAttributes);
    }


    public ComputeFreightDto updateCateGoryProById(ComputeFreightDto dto) {
        try {

            // 获取商品
            ErpCollectProduct product = JSONObject.parseObject(dto.getProduct().toString(), ErpCollectProduct.class);
            // 获取扩展信息
            ErpCollectProductExpand expand = JSONObject.parseObject(dto.getProductExpand().toString(), ErpCollectProductExpand.class);
            //获取sku信息
            List<ErpCollectProductSku> skuList = JSONArray.parseArray(dto.getProductSkuList().toJSONString(), ErpCollectProductSku.class);


            // 判断是否是多规格，不是就跳过
            ErpCollectProductSku erpCollectProductSku = skuList.get(0);
            String skuPropertyIds = erpCollectProductSku.getSkuPropertyIds();
            if (!skuPropertyIds.contains(";"))
                return null;

            // 多规格合并为单规格
            String skuProperty = expand.getSkuProperty();

            // 解析合并
            Map<String, Long> map = new HashMap<>();

            Long value = 30000l;

            List<Dict> propertyList = JsonUtils.parseArrayMap(skuProperty);
            Dict dict = propertyList.get(0);
            List<HashMap<String, Object>> oneValue = (List<HashMap<String, Object>>) dict.get("list");

            List<HashMap<String, Object>> res = new ArrayList<>();
            for (int i = 1; i < propertyList.size(); i++) {
                Dict dict1 = propertyList.get(i);
                List<HashMap<String, Object>> otherValue = (List<HashMap<String, Object>>) dict1.get("list");

                // 合并
                for (HashMap<String, Object> map1 : oneValue) {
                    String name = (String) map1.get("name");
                    Object value1 = map1.get("value");

                    for (HashMap<String, Object> map2 : otherValue) {

                        HashMap<String, Object> newHashMap = new HashMap<>();

                        String name2 = (String) map2.get("name");

                        String nameres = name + " " + name2;
                        newHashMap.put("name", nameres);
                        newHashMap.put("value", value);

                        Object value2 = map2.get("value");

                        String key = value1 + "-" + value2;
                        map.put(key, value);

                        value++;

                        res.add(newHashMap);
                    }
                }
            }

            dict.put("list", res);
            propertyList = new ArrayList<Dict>();
            propertyList.add(dict);
            expand.setSkuProperty(JsonUtils.toJsonString(propertyList));

            // 修改sku
            for (ErpCollectProductSku sku : skuList) {

                String nameId = "";
                String valueId = "";

                // 获取sku属性
                String skuPropertyIds2 = sku.getSkuPropertyIds();
                String[] split = skuPropertyIds2.split(";");
                for (int i = 0; i < split.length; i++) {
                    String[] split2 = split[i].split(":");
                    if (i == 0) {
                        nameId = split2[0];
                    }
                    valueId = valueId + split2[1] + "-";
                }

                valueId = valueId.substring(0, valueId.length() - 1);

                // 获取新的id
                Long long1 = map.get(valueId);

                String newSkuPropertyIds = nameId + ":" + long1;
                sku.setSkuPropertyIds(newSkuPropertyIds);

            }

            // 更新扩展表和sku表
//            erpCollectProductExpandMapper.updateById(expand);
//            erpCollectProductSkuMapper.updateBatchById(skuList);

            //重新设为0

            dto.setProduct(JSONObject.parseObject(JSONObject.toJSONString(product)));
            dto.setProductExpand(JSONObject.parseObject(JSONObject.toJSONString(expand)));
            dto.setProductSkuList(JSONArray.parseArray(JSONObject.toJSONString(skuList)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dto;
    }


}
